package net.thermetics.fx.controllers;

import java.util.Date;

import javax.servlet.http.HttpServletResponse;

import net.thermetics.fx.services.DynamicResourceService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * Controller that serves up dynamic, non-caching resources.
 * @author projectmoon
 *
 */
@Controller
public class ResourceController extends AbstractController {
	@Autowired
	private DynamicResourceService resourceService;
	
	/**
	 * Load a non-caching script resource.
	 * @param widget
	 * @param script
	 * @param model
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/widgets/{widget}/{script}", method = RequestMethod.GET)
	public String getScript(@PathVariable String widget, @PathVariable String script, Model model, final HttpServletResponse response) {
		response.setHeader("Cache-Control", "no-cache, must-revalidate");
		response.setHeader("Expires", new Date().toString());
		
		String code = resourceService.getScript(widget, script);
		model.addAttribute("code", code);
		return "widgets/widget_externalScript";
	}
	
	/**
	 * Load a widget.
	 * @param widget
	 * @param model
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/widgets/{widget}", method = RequestMethod.GET)
	public String getScript(@PathVariable String widget, Model model, final HttpServletResponse response) {
		response.setHeader("Cache-Control", "no-cache, must-revalidate");
		response.setHeader("Expires", new Date().toString());
		
		String code = resourceService.getScript(widget, "widget");
		model.addAttribute("code", code);
		return "widgets/widget_container";
	}
	
	/**
	 * Load a stylesheet.
	 * @param stylesheet
	 * @param model
	 * @return
	 */
	@RequestMapping("/widgets/{widget}/styles/{stylesheet}")
	public String getStylsheet(@PathVariable String widget, @PathVariable String stylesheet, Model model) {
		String code = resourceService.getStylesheet(widget, stylesheet);
		model.addAttribute("code", code);
		return "widgets/caching_stylesheet";
	}
}
